var id = 0;

function nextId() {
  id++;
  return 'p' + id;
}

function Product(name, weight, price) {
  this.id = nextId()
  this.name = name
  this.weight = weight || ''
  this.price = price || 0
}

var products = [
  new Product('iphone', '300克', 8999),
  new Product('kindle', '200克', 899),
  new Product('huawei', '300克', 2888)
]

module.exports = {
  getProducts: () => {
    return products
  },
  getProduct: (id) => {
    for (let i = 0; i < products.length; i++) {
      if (products[i].id === id) {
        return products[i]
      }
    }
    return null
  },
  creatProduct: (product) => {
    var p = new Product(product.name, product.weight, product.price)
    if (p.name) {
      products.push(p)
      return p
    }
  },
  deleteProduct: (id) => {
    var index = -1,
      i;
    for (var i = 0; i < products.length; i++) {
      if (products[i].id === id) {
        index = i;
        break;
      }
    }
    if (index > -1) {
      return products.splice(index, 1)[0]
    }
    return null
  }
}